package com.mojo.concurrent.concurrent_07_pool;

import java.util.concurrent.*;

/**
 * 固定线程池示例
 * <p>
 * 1、核心线程数等于最大线程数
 * 2、keepAliveTime时间为0L:多余空闲线程立即终止，但是最大
 * 3、使用LinkedBlockingQueue无界线性阻塞队列。
 * 4、因为使用无界队列，所以运行中的线程池不会拒绝任务
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2023, 广州九尾信息科技有限公司
 * @date 2023/2/17 16:26
 */
public class FixedThreadPool1 {
    // LinkedBlockingQueues任务队列
    static ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(2, new MyThreadFactory());

    public static void main(String[] args) {
        System.out.println("已执行任务数1：" + executorService.getTaskCount());
        for (int i = 0; i < 500; i++) {
            int finalI = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName() + "任务" + finalI);
                }
            });
        }
        System.out.println("=============================================");
        System.out.println("已执行任务数1：" + executorService.getCompletedTaskCount());
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("已执行任务数2：" + executorService.getCompletedTaskCount());
        System.out.println("曾创建的最大线程数量：" + executorService.getLargestPoolSize());
        System.out.println("线程池的线程数量：" + executorService.getPoolSize());

        Future<?> future = executorService.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(">>" + Thread.currentThread().getName());
            }
        });
        try {
            System.out.println(future.get());
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
        executorService.shutdown();
        System.out.println(executorService.isTerminated());
    }
}
